class UserController < ApplicationController
	#layout 'standard'
	before_filter :login_required, :only=>[ 'change_password', 'hidden', 'welcome', 'show', 'edit']

	def signup
		@user = User.new(params[:user])
		if request.post?
			@user.password = "abcdefg"
			@user.password_confirmation = "abcdefg"
			@user.active = true
			if @user.save
				@user.send_new_password
				flash[:message] = "Password has been sent to your Email."
				redirect_to :action => "login"
				Usergroup.new(:group_id => 1, :user_id=> @user.id).save
				#User.find_by_sql("Insert into usergroups (group_id, user_id) value (1, #{@user.id})")
				return
				session[:user] = User.authenticate(@user.login, @user.password)
				flash[:message] = "Signup successful"
				redirect_to :action => "welcome"
			else
				flash[:warning] = "Signup unsuccessful"
			end
		end
	end

	def login
		if request.post?
			if session[:user] = User.authenticate(params[:user][:login], params[:user][:password])
				flash[:message]  = "Login successful"
				redirect_to_stored
			else
				flash[:warning] = "Login unsuccessful"
			end
		else
			redirect_to :action =>"welcome" if session[:user]
		end
	end

	def logout
		session[:user] = nil
		flash[:message] = 'Logged out'
		redirect_to :action => 'login'
	end

	def forgot_password
		if request.post?
			u= User.find_by_email(params[:user][:email])
			if u and u.send_new_password
				flash[:message]  = "A new password has been sent by email."
				redirect_to :action=>'login'
			else
				flash[:warning]  = "Couldn't send password"
			end
		end
	end
  
	def change_password
		@user=session[:user]
		if request.post?
			if User.encrypt(params[:user][:oldpassword], @user.salt) != @user.hashed_password
				flash[:warning]="Old Password no Match"
				return
			end
			#puts "<change_password>  old password dah lepas"
			@user.update_attributes(:password => params[:user][:password], 
									:password_confirmation => params[:user][:password_confirmation])
			if @user.save
				flash[:message]="Password Changed"
				redirect_to :action => 'show'
			end
		end
	end

	def welcome
	end
	def hidden
	end
  
  	def show
		@user = User.find(session[:user].id)
  	end
  	
	def edit
		#@user = User.find(:first, :conditions => ["id = ?",params[:id]])
		@user = User.find(session[:user].id)
		if @user.nil?
			redirect_to :action => 'welcome' and return
		end
		@user.email_confirmation = @user.email
		
		hashPass_ori = @user.hashed_password
		#puts "<update> #{hashPass_ori}  #{@user.login} #{@user.email}"
		if request.post?
			@user.update_attributes(params[:user])
			@user.password = "dummy"
			@user.password_confirmation = "dummy"
			@user.hashed_password = hashPass_ori 
			if @user.save()
				flash[:message] = "User information update."
			else
				#puts "<update>1 #{hashPass_ori}  #{@user.login}"
				flash[:warning] = "Update unsuccessful"
				puts "<update>2 #{@user.hashed_password}    #{@user.login} #{@user.email}"
			end
		end
	end
	  
end
